<template>
    <div class="user">
      <el-row>
        <el-col :span="24">
          <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>权限管理</el-breadcrumb-item>
          <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">     
          <el-button type="success" plain @click="addDialogFormVisible=true">添加角色</el-button>
        </el-col>
      </el-row>

      <el-table
        class="margin-20"
        v-loading="loading"
        :data="roleList"
        border
        style="width: 100%">
        <!--展开行-->
         <el-table-column type="expand">
          <template slot-scope="scope">
             <el-row v-for="one in scope.row.children" :key="one.id">
                <el-col :span="4">
                    <el-tag closable  @close="deleleRight(scope.row,one.id)">{{one.authName}}</el-tag>
                    <i class="el-icon-arrow-right" v-if="one.children.length !=0"></i>
                </el-col>
                <el-col :span="20">
                    <el-row v-for="two in one.children" :key="two.id">
                        <el-col :span="4">
                          <el-tag closable type="success"  @close="deleleRight(scope.row,two.id)">{{two.authName}}</el-tag> 
                          <i class="el-icon-arrow-right" v-if="two.children.length !=0"></i>
                        </el-col>
                        <el-col :span="20">
                          <el-row v-for="three in two.children" :key="three.id">
                              <el-col :span="4">
                                <el-tag closable type="warning"  @close="deleleRight(scope.row,three.id)">{{three.authName}}</el-tag> 
                              </el-col>
                          </el-row>
                        </el-col>
                    </el-row>
                </el-col>
             </el-row>
             <el-row v-if="scope.row.children.length == 0">
               <el-col :span="24">该角色没有分配权限,请前外分配</el-col>
             </el-row>
          </template>
        </el-table-column>
        <!--展开行-->
        <el-table-column
          prop="roleName"
          label="角色名称"
          width="180">
        </el-table-column>
        <el-table-column
          prop="roleDesc"
          label="描述"
          width="180">
        </el-table-column>              
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain icon="el-icon-edit" @click="showEditDialog(scope.row)"></el-button>      
            <el-button size="mini" type="danger" plain icon="el-icon-delete" @click="showDeleteDialog(scope.row)"></el-button>    
            <el-button size="mini" type="warning" plain icon="el-icon-check" @click="showAuthDialog(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="1"
          :page-sizes="[1,10, 20, 30, 40]"
          :page-size="1"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
 
      <!-- 添加角色对话框 -->
      <el-dialog title="添加角色" :visible.sync="addDialogFormVisible">
        <el-form :model="addForm" label-width="80px" :rules="rules" ref="addRoleForm">
          <el-form-item label="角色名称" prop="username">
            <el-input v-model="addForm.roleName" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="password">
            <el-input v-model="addForm.roleDesc" auto-complete="off"></el-input>
          </el-form-item>        
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoleSubmit('addRoleForm')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑角色对话框 -->
      <el-dialog title="编辑角色" :visible.sync="editDialogFormVisible">
        <el-form :model="editForm" label-width="80px" :rules="rules" ref="editRoleForm">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName" auto-complete="off" ></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRoleSubmit('editRoleForm')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配权限对话框 -->
      <el-dialog title="分配权限" :visible.sync="grantDialogFormVisible">
        <el-tree
          :data="authList"
          show-checkbox
          default-expand-all
          node-key="id"
          ref="tree"
          :default-checked-keys="selectedAuths"  
          :props="defaultProps"
          >

        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="grantDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="grantAuthSubmit()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
</template>


<script>
import {getRoleList,addRole,getRoleById,editRole,delRole,deleteRoleAuth,getAuthList,grantRoleAuth} from '@/api/index.js'

export default {
    data: function(){
        return {
         authList: [{
          id: 1,"authName":"订单管理","path":"goods","pid":0,
          children:[{
            id: 4,
            authName: '二级 1-1',
            children: [{
              id: 9,
              authName: '三级 1-1-1'
            }, {
              id: 10,
              authName: '三级 1-1-2'
            }]
          }]
        }],
        defaultProps: {
          children: 'children',
          label: 'authName'
        },
        selectedAuths:[],  //保存默认选中的权限id
        currentRole:{}, //保存正在被操作的角色id
        loading: false,
        roleList: [
          {"id":1,"roleName":"超级管理员1","roleDesc":"admin"},
          {"id":2,"roleName":"超级管理员2","roleDesc":"admin"}
          ],
        query: '',
        total: 0,
        pagesize: 1,
        pagenum: 1,

        //###添加数据
        addDialogFormVisible: false,
        addForm: {
          roleName:'',
          roleDesc:'',
          roleId:0
        },
        rules: {
          roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' }
          ],
          roleDesc: [
            { required: true, message: '请输入角色描述', trigger: 'blur' }
          ]      
        },
        //###修改数据
        editDialogFormVisible: false,
        editForm: {
          roleName: '',
          roleDesc: '',
          id:0
        },
        //分配角色
        grantDialogFormVisible: false,
        grantForm: {},
        roleId: '',
        roleList: [],
      }
    },
    created:function(){
      //网页加载时调用initList方法获取数据
      this.initList()
    },
    methods: {    
        //获取最新列表数据
        initList:function(){
            //显示loading效果
            this.loading = false
            getRoleList().then(res=>{
              if(res.meta.status === 200){
                  this.roleList = res.data
              }
            })
            
        },
        //添加角色
        addRoleSubmit:function(){
            this.$refs.addRoleForm.validate((valid)=>{
              if(valid){
                addRole(this.addForm).then(res=>{
                  if(res.meta.status === 201){
                    this.$message({
                      type:'success',
                      message:res.meta.msg
                    })
                    this.addDialogFormVisible = false
                    this.initList()
                  }else{
                    this.$message({
                      type:'error',
                      message:res.meta.msg
                    })
                  }
                })
              }
            })
        },
        //删除
        showDeleteDialog:function(row){
            this.$confirm("确定删除").then(_=>{
              delRole(row.id).then(res=>{
                if(res.meta.status === 200){
                    this.$message({
                    type:'success',
                    message:'删除成功!'
                  })
                  window.location.reload()
                }
               
              }).catch(_=>{
                this.$message({
                  type:'info',
                  message:'已取消删除'
                })
              })
            });
        },
        //显示编辑角色对话框
        showEditDialog: function (row) {
          this.editDialogFormVisible = true
          //根据id获取角色信息
          getRoleById({id:row.id}).then(res=>{
              if(res.meta.status === 200){
              this.editForm.roleName = res.data.roleName
              this.editForm.roleDesc = res.data.roleDesc
              this.editForm.id = res.data.roleId
            }
          });         
        },
        //删除角色所拥有权限
        deleleRight:function(row,authId){
            deleteRoleAuth({roleId:row.id,rightId:authId}).then(res=>{
                if(res.meta.status === 200){
                  //  this.initList()
                   row.children = res.data
                }else{
                  this.$message({
                    type:'error',
                    message:res.meta.msg
                  })
                }
            })
        },
        //
        editRoleSubmit:function(){
            this.$refs.editRoleForm.validate((valid)=>{
              if(valid){
                //
                editRole(this.editForm).then(res=>{
                    if(res.meta.status === 200) {
                        this.$message({
                          type:'success',
                          message:res.meta.msg
                        })
                        this.editDialogFormVisible = false
                        this.initList()
                    }else{
                      this.$message({
                        type:'error',
                        message:res.meta.msg
                      })
                    }
                })
              }
            })
        },
        //显示分配权限对话框
        showAuthDialog (row) {
            this.grantDialogFormVisible = true
            getAuthList({type:'tree'}).then(res=>{
              console.log(res)
              if(res.meta.status === 200){
                this.authList = res.data
              }else{
                this.$message({
                  type:'error',
                  message:res.meta.msg
                })
              }            
            })    
            //默认选中
            this.selectedAuths = []
            row.children.forEach(first=>{
              if(first.children && first.children.length !==0){
                first.children.forEach(two=>{
                  if(two.children && two.children.length !==0){
                    two.children.forEach(three=>{
                      this.selectedAuths.push(three.id)
                    })
                  }
                })
              }
            })   
            
          //保存点击的角色（currentRole）
          this.currentRole = row
        },   
        //授权
        grantAuthSubmit:function(){
            //获取选中数据
            var rids = this.$refs.tree.getCheckedKeys().join(',')
            grantRoleAuth(this.currentRole.id,{rids:rids}).then(res=>{
               if(res.meta.status === 200){
                 this.$message({
                   type:'success',
                   message:res.meta.msg
                 })
                 this.grantDialogFormVisible = false
                 this.initList()
               }
            })
        },   
        handleSizeChange (val) {
          this.pagesize = val;
          this.initList()
          console.log(`每页 ${val} 条`)
        },
        handleCurrentChange (val) {
          //更改当前页
          this.pagenum = val;
          //获取新页码数据
          this.initList()
          // console.log(`当前页: ${val}`)
        }
    }
}
</script>

<style scoped>
  .user .margin-20 { 
    margin: 20px 0;
  }
  .user .search-input {
    width: 300px;
  }
  .user .page {
    padding: 5px 0;
    background-color: #D3DCE6;
  }
</style>